package cn.qfengx.token;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;

/**
 * token获取示例
 * Created by YeShengtao on 2020/11/19 9:21
 */
public class TokenDemo {

    private static String pub_key = "";
    private static String priv_key = "";
    private static String host = "http://localhost:89";

    public static void main(String[] args) {
        // 配置提供的固定值
        String appid = "EEAA5436-7577-4BE0-8C6C-89E9D88805EA";

        JSONObject jsonObject = register(appid);
        // 获取注册返回的系统公钥spk
        String spk = jsonObject.getString("spk");
        // 获取注册返回的secrit
        String secrit = jsonObject.getString("secrit");
        System.out.println("spk => " + spk);
        System.out.println("secrit => " + secrit);
        RSA rsa = new RSA(null, spk);
        String encryptSecret = rsa.encryptBase64(secrit, CharsetUtil.CHARSET_UTF_8, KeyType.PublicKey);
        JSONObject tokenObj = applytoken(appid, encryptSecret);
        String token = tokenObj.getString("token");
        System.out.println("token => " + token);
    }

    // 注册公钥
    public static JSONObject register(String appid) {
        RSA rsa = new RSA();
        pub_key = rsa.getPublicKeyBase64();
        priv_key = rsa.getPrivateKeyBase64();
        //调用ECOLOGY系统接口进行注册
        String data = HttpRequest.post(host + "/api/ec/dev/auth/regist")
                .header("appid", appid)
                .header("cpk", pub_key)
                .timeout(2000)
                .execute().body();
        return JSONObject.parseObject(data);
    }

    // 获取token
    public static JSONObject applytoken(String appid, String secret) {
        String data = HttpRequest.post(host + "/api/ec/dev/auth/applytoken")
                .header("appid", appid)
                .header("secret", secret)
                .timeout(2000)
                .execute().body();
        return JSONObject.parseObject(data);
    }
}
